<template>
  <div id="app">
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :before-upload="beforeAvatarUpload"
      :http-request="uploadImage"
      :file-list.sync="fileList"
      :limit="2"
    >
      <i class="el-icon-upload2">
        <p>上传文件</p>
      </i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img
        width="100%"
        :src="dialogImageUrl"
        alt=""
      >
    </el-dialog>
    <p class="exeg">注：图片大小不超过5M；仅能上传 PNG JPEG JPG类型图片；建议上传400*300尺寸的图片；最多上传2张</p>
  </div>
</template>
<script>
import COS from 'cos-js-sdk-v5'
export default {
  props: {
    value: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      imageUrl: '',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      fileList: []
    }
  },
  mounted() {
    this.value.forEach(url => {
      const file = { name: url, url: url }
      this.fileList.push(file)
    })
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    uploadImage(params) {
      console.log(params.file)
      const cos = new COS({
        SecretId: 'AKIDb8UhiV5TffWGtKbficJolV0MVSCj4B40',
        SecretKey: 'wgCVbYHmmZ8TbYIo6B2f6IQO9ey4xfBU'
      }) // 完成cos对象的初始化
      cos.putObject({
        Bucket: 'yd-1318882608',
        Region: 'ap-beijing',
        Key: params.file.name,
        StorageClass: 'STANDARD',
        Body: params.file
      }, (err, data) => {
        if (data.statusCode === 200 && data.Location) {
          this.$emit('input', [...this.value, 'http://' + data.Location])
        } else {
          this.$message.error(err.Message)
        }
      })
    },
    beforeAvatarUpload(file) {
      console.log(file)
      const isJPG = '[image/png,image/jpg,image/jpeg]'.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG PNG JPEG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="less" scoped>
.exeg {
  font-size: 12px;
  color: #bac0cd;
  display: inline-block;
  line-height: 17px;
  font-weight: 400;
}
::v-deep .el-upload--picture-card{
  margin-left: 10px;
}
.el-icon-upload2  {
      margin-top: 44px;
  color: #2a2929;
  p {
    font-size: 14px;
  }
}
</style>
